package accountandrole

import (
	//"fmt"
	"jiabo/appframework/libs/db"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
)

type Account struct {
	Id        bson.ObjectId `bson:"_id,omitempty" json:"-"`
	UserName  string        `bson:"userName" json:"userName"`
	Password  string        `bson:"password" json:"password"`
	Belongsto []Role        `bson:"belongsto" json:"belongsto"`
	Fullname  string        `bson:"fullname" json:"fullname"`
	Email     string        `bson:"email" json:"email"`
	Address   string        `bson:"address" json:"address"`
	City      string        `bson:"city" json:"city"`
	Country   string        `bson:"country" json:"country"`
}

//判断数据库中是否存在用户名相同的账号
func (account *Account) CheckIfAccountExist() (result bool, searchErr error) {
	searchErr = nil
	searchResults := Account{}

	query := func(c *mgo.Collection) error {
		fn := c.Find(bson.M{"userName": account.UserName}).One(&searchResults)
		return fn
	}
	search := func() error {
		return db.WithCollection("accounts", query)
	}
	err := search()
	if err != nil {
		searchErr = err
	}
	if searchResults.Id != "" {
		result = true
	} else {
		result = false
	}
	return
}

func (account *Account) Save() error {
	ifAccountExist, err := account.CheckIfAccountExist()
	if err != nil {
		//return err
	}
	if ifAccountExist {
		update := func(c *mgo.Collection) error {
			fn := c.Update(bson.M{"userName": account.UserName}, account)
			return fn
		}

		updateExec := func() error {
			return db.WithCollection("accounts", update)
		}

		err := updateExec()
		return err
	} else {
		insert := func(c *mgo.Collection) error {

			fn := c.Insert(account)
			return fn
		}

		insertExec := func() error {
			return db.WithCollection("accounts", insert)
		}

		err := insertExec()
		return err
	}
	return nil
}

func (account *Account) Delete() error {
	ifAccountExist, err := account.CheckIfAccountExist()
	if err != nil {
		return err
	}
	if ifAccountExist {
		delet := func(c *mgo.Collection) error {
			fn := c.Remove(bson.M{"userName": account.UserName})
			return fn
		}

		deleteExec := func() error {
			return db.WithCollection("accounts", delet)
		}

		err := deleteExec()
		return err
	}
	return nil
}

func GetAccountByUserName(userName string) (account Account, searchErr error) {
	searchErr = nil
	searchResults := Account{}

	query := func(c *mgo.Collection) error {
		fn := c.Find(bson.M{"userName": userName}).One(&searchResults)
		return fn
	}
	search := func() error {
		return db.WithCollection("accounts", query)
	}
	err := search()
	if err != nil {
		searchErr = err
		return
	}

	if searchResults.Id != "" {
		account = searchResults
		return
	}
	return
}
